# encoding=utf-8
import eel
import requests
import time
import threading
import win32api
import win32con
import json

# 定义html文件所在文件夹名称
eel.init('views')

# 向前端输出日志
def toMsg(msg):
    return "%s ：%s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),msg)

# 课堂学习
def studyOne(index,minute,recordId,headers,title):
    flag = True
    Continue_t = int(round(time.time() * 1000))
    UploadStudyRecordContinueApi = "https://degree.qingshuxuetang.com/cqust/Student/Course/UploadStudyRecordContinue?_t=%s" % Continue_t
    params = {
        "end":False,
        "recordId": recordId,
        "position": 120,
        "timeOutConfirm": False  # 固定参数
    }
    try:
        headers["Content-Type"] = "application/x-www-form-urlencoded"
        res = requests.post(url=UploadStudyRecordContinueApi, params=params, headers=headers)
        resjson = res.json()
        if resjson["message"] == "成功":
            eel.js_fun(toMsg('请求成功，已学习 %s 分钟' % (str(index * 2))), True)
            # # 计算百分比进度，通知前端
            # eel.js_speed(title,index * 2 / minute * 100,index * 2)
        else:
            eel.js_fun(toMsg('请求失败，%s，系统将自动学习下一章节，注意：请勿在青书网页端播放课程，将顶掉当前设备。' % (resjson["message"])), True)
            flag = False
    except:
        pass
    return flag
def runStart(data):
    type = data["type"]
    cookie = data["cookie"]
    selarr = data["selarr"]
    minute = int(data["minute"])
    '''
    开始学习
    '''
    begin_t = int(round(time.time() * 1000))
    UploadStudyRecordBeginApi = "https://degree.qingshuxuetang.com/cqust/Student/Course/UploadStudyRecordBegin?_t=%s" % (
    begin_t)
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75",
        "Cookie": "%s" % cookie,
        "Referer": "https://degree.qingshuxuetang.com/cqust/Student/Course/CourseShow",
        "Content-Type": "application/json"
    }
    contentType = 11
    if type == "zj1": # 学习政治
        courseId = "2781"
        periodId = "15"
    elif type == "zj2": # 学习数学
        courseId = "2805"
        periodId = "15"
    elif type == "zj3":# 学习英语
        courseId = "2769"
        periodId = "15"
    elif type == "zj4":# 学习C语言
        courseId = "2009"
        periodId = "15"
    elif type == "zj2-1":# 社交礼仪(专升本)
        courseId = "2233"
        periodId = "16"
    elif type == "zj2-2":# 线性代数(专升本)
        courseId = "1885"
        periodId = "16"
    elif type == "zj2-3":# Web程序设计基础(专升本)
        courseId = "2022"
        periodId = "16"
    elif type == "zj2-4":# 数据结构(专升本)
        courseId = "1769"
        periodId = "16"
    elif type == "zj2-5":# 网络安全技术(专升本)
        courseId = "2260"
        periodId = "16"

    elif type == "zj3-1":# 计算机组成原理(专升本)
        courseId = "1915"
        periodId = "17"
    elif type == "zj3-2":# 大学物理(专升本)
        courseId = "2107"
        periodId = "17"
    elif type == "zj3-3":# 应用文写作(专升本)
        courseId = "1733"
        periodId = "17"
    elif type == "zj3-4":# Java程序设计(专升本)
        courseId = "2016"
        periodId = "17"
    elif type == "zj3-5":# 数据库原理及应用(专升本)
        courseId = "1767"
        periodId = "17"
    elif type == "zj3-6":# 人工智能(专升本)
        courseId = "2051"
        periodId = "17"
    
    elif type == "zj4-1":# 计算机网络(专升本)
        courseId = "2271"
        periodId = "18"
    elif type == "zj4-2":# 软件测试技术(专升本)
        courseId = "2280"
        periodId = "18"
    elif type == "zj4-3":# Java高级网络编程(专升本)
        courseId = "2018"
        periodId = "18"
    elif type == "zj4-4":# 操作系统原理(专升本)
        courseId = "2147"
        periodId = "18"
    elif type == "zj4-5":# 中国近代史纲要(专升本)
        courseId = "3220"
        periodId = "18"
    elif type == "zj5-1":# 毕业设计（论文）(专升本)
        courseId = "2164"
        periodId = "19"
    elif type == "zj5-2":# 毕业实习(专升本)
        courseId = "2160"
        periodId = "19"
    elif type == "zj1-jc":# 政治课程教材
        courseId = "2781"
        periodId = "15"
        contentType = 12
    elif type == "zj2-jc":# 数学课程教材
        courseId = "2805"
        periodId = "15"
        contentType = 12
    elif type == "zj3-jc":# 英语课程教材
        courseId = "2769"
        periodId = "15"
        contentType = 12
    elif type == "zj4-jc":# C语言课程教材
        courseId = "2009"
        periodId = "15"
        contentType = 12
    elif type == "zj2-1-jc":# 社交礼仪(专升本) 课程教材
        courseId = "2233"
        periodId = "16"
        contentType = 12
    elif type == "zj2-2-jc":# 线性代数(专升本) 课程教材
        courseId = "1885"
        periodId = "16"
        contentType = 12
    elif type == "zj2-3-jc":# Web程序设计基础 课程教材
        courseId = "2022"
        periodId = "16"
        contentType = 12
    elif type == "zj2-4-jc":# 数据结构 课程教材
        courseId = "1769"
        periodId = "16"
        contentType = 12
    elif type == "zj2-5-jc":# 网络安全技术 课程教材
        courseId = "2260"
        periodId = "16"
        contentType = 12
    elif type == "zj3-1-jc":# 计算机组成原理(专升本) 课程教材
        courseId = "1915"
        periodId = "17"
        contentType = 12
    elif type == "zj3-2-jc":# 大学物理(专升本) 课程教材
        courseId = "2107"
        periodId = "17"
        contentType = 12
    elif type == "zj3-3-jc":# 应用文写作(专升本) 课程教材
        courseId = "1733"
        periodId = "17"
        contentType = 12
    elif type == "zj3-4-jc":# Java程序设计(专升本) 课程教材
        courseId = "2016"
        periodId = "17"
        contentType = 12
    elif type == "zj3-5-jc":# 数据库原理及应用(专升本) 课程教材
        courseId = "1767"
        periodId = "17"
        contentType = 12
    elif type == "zj3-6-jc":# 人工智能（专升本） 课程教材
        courseId = "2051"
        periodId = "17"
        contentType = 12
    elif type == "zj4-1-jc":# 计算机网络(专升本) 课程教材
        courseId = "2271"
        periodId = "18"
        contentType = 12
    elif type == "zj4-2-jc":# 软件测试技术(专升本) 课程教材
        courseId = "2280"
        periodId = "18"
        contentType = 12
    elif type == "zj4-3-jc":# Java高级网络编程(专升本) 课程教材
        courseId = "2018"
        periodId = "18"
        contentType = 12
    elif type == "zj4-4-jc":# 操作系统原理(专升本) 课程教材
        courseId = "2147"
        periodId = "18"
        contentType = 12
    elif type == "zj4-5-jc":# 中国近代史纲要(专升本) 课程教材
        courseId = "3220"
        periodId = "18"
        contentType = 12
    elif type == "zj5-1-jc":# 毕业设计（论文）(专升本) 课程教材
        courseId = "2164"
        periodId = "19"
        contentType = 12
    for index in range(len(selarr)):
        contentId = selarr[index]["id"]
        title = selarr[index]["title"]
        params = {
            "schoolId": "2921",  # 固定参数
            "classId": "251",  # 固定参数
            "courseId": "%s" % courseId,
            "contentId": "%s" % contentId,  # 课程编号
            "contentType": contentType,  # 固定参数
            "periodId": "%s" % periodId,
            "position": 0  # 固定参数
        }
        try:
            headers["Content-Type"] = "application/json"
            res = requests.post(url=UploadStudyRecordBeginApi, json=params, headers=headers)
            print(res)
            resjson = res.json()
            if resjson["message"] == "成功":
                eel.js_fun(toMsg('开始学习【%s】' % (title)), True)
                eel.js_speed(title,minute,'on')  # 通知前端显示进度
                recordId = resjson["data"]
                a = 1
                while a < (minute/2 + 1):  # 循环请求次数
                    t1 = int(time.time())
                    while True:
                        t2 = int(time.time())
                        global stop_threads
                        if stop_threads:
                            # 结束线程
                            eel.js_fun(toMsg('已结束本次学习'), False)
                            return
                        else:
                            if t2 - t1 >= 120:
                                callstatus = studyOne(a,minute,recordId, headers, title)
                                a = a + 1
                                break
                    if not callstatus:  # 当出现请求失败时，结束当前章节
                        break
            else:
                eel.js_fun(toMsg('学习中断，请重新登录青书' % (title)), False,'error')
        except Exception as e:
            eel.js_fun(toMsg('程序异常，请重新登录青书'), False,'error')
            break
        if callstatus:
            eel.js_fun(toMsg('该章节已完成学习'), True)
            eel.js_speed('',minute,'off',contentId)
    eel.js_fun(toMsg('所选章节都已完成学习'), False)

# 线程开关
stop_threads = False

@eel.expose # 使用装饰器,类似flask里面对路由的定义
def py_runStart(data):# 开始线程
    global stop_threads
    stop_threads = False
    # 创建线程
    t=threading.Thread(target=runStart,args=(data,))
    # 设置线程为后台线程
    t.setDaemon(True)
    t.start()
@eel.expose
def py_runOff(page,b):# 结束线程
    if page == "view.html":
        global stop_threads
        stop_threads = True
@eel.expose
def py_login():# 前端请求获取二维码参数
    eel.js_fun(toMsg('开始请求登录青书'), True)
    GetQRCodeApi_t1 = int(round(time.time() * 1000))
    GetQRCodeApi_t2 = int(round((time.time() + 300) * 1000))
    GetQRCodeApi = "https://www.qingshuxuetang.com/Svc/GetQRCode?_=%s&_t=%s" % (GetQRCodeApi_t1, GetQRCodeApi_t2)
    res = requests.get(url=GetQRCodeApi)
    resjson = res.json()
    eel.js_makeQrocde(resjson)
@eel.expose
def py_checklogin(code):# 检查是否登录
    GetQRCodeStatusApi_t1 = int(round(time.time() * 1000))
    GetQRCodeStatusApi_t2 = int(round((time.time() + 300) * 1000))
    GetQRCodeStatusApi = "https://www.qingshuxuetang.com/Svc/GetQRCodeStatus?code=%s&_=%s&_t=%s" % (code,GetQRCodeStatusApi_t1,GetQRCodeStatusApi_t2)
    res = requests.get(url=GetQRCodeStatusApi)
    resjson = res.json()
    if resjson["hr"] == 0 and resjson["data"] == 1:
        # 请求获取cookie
        LoginByQRCodeApi = "https://www.qingshuxuetang.com/LoginByQRCode?_t=%s" % (int(round(time.time() * 1000)))
        response = requests.post(url=LoginByQRCodeApi,params={"code":code})
        cookies_json = response.cookies.get_dict()
        # 储存cookie
        file = open('cookie.json','w')
        json.dump(cookies_json,file,ensure_ascii=False)
        file.close()
        # 切回第一个句柄
        eel.js_setCookie(cookies_json)
        eel.js_fun(toMsg('登录成功，请开始学习吧'), True)
@eel.expose
def py_check():
    file = open('cookie.json','r')
    cookies_json = json.load(file)
    file.close()
    if cookies_json:
        eel.js_check(cookies_json)
    
# 获取屏幕分辨率
x = win32api.GetSystemMetrics(win32con.SM_CXFULLSCREEN)
y = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
# 启动的函数调用放在最后,port=0表示使用随机端口,size=(宽,高)
eel.start('main.html', port=0, size=(800,750),position=((x-800)/2,(y-750)/2),close_callback=py_runOff)
